/**
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { request, signin, toMd5 } from '@/soar';
import sm2 from '@/soar/js_sdk/sm2';
import { sm2DynamicPKI } from './common';

const baseUrl = '/system/login';

/**
 * 使用密码登录
 * @param parameter {
 *     username： 用户名
 *     password：密码（MD5值）
 *     captcha：验证码
 * }
 * @returns {*}
 */
export function account(parameter: any): Promise<any> {
  return new Promise((resolve, reject) => {
    sm2DynamicPKI('login')
      .then((res) => {
        parameter.account = `04${sm2.doEncrypt(parameter.account.trim(), res)}`;
        parameter.password = `04${sm2.doEncrypt(toMd5(parameter.password.trim()), res)}`;
        parameter.captcha = parameter.captcha?.trim();
        parameter.encrypted = true;
        request
          .post(`${baseUrl}/account`, {
            title: '登录',
            successMsg: '欢迎回来',
            data: parameter,
          })
          .then((res) => {
            signin(res);
            resolve(res);
          })
          .catch(reject);
      })
      .catch(reject);
  });
}

/**
 * 扫码登录
 * @param code
 */
export function codeLogin(code: string) {
  return request
    .get(`${baseUrl}/code`, {
      title: '登录',
      successMsg: false,
      errorMsg: false,
      params: { code },
    })
    .then((res) => {
      console.log(res)
      signin(res);
      return res;
    });
}
